package skiree.host.abetsy.service.util;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import skiree.host.abetsy.model.LocalAnime;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

public class DouBanUtil {

    public static void douBanLink(LocalAnime localAnime) {
        JSONObject data = douBanSelect(localAnime.getTitle(), localAnime.getSeason());
        if (data != null) {
            String url = data.getStr("url");
            Matcher mDouBanId = Pattern.compile("https://movie.douban.com/subject/(\\d+)/").matcher(url);
            if (mDouBanId.find()) {
                if (StrUtil.isBlank(localAnime.getImg())){
                    supplementAnimeCover(localAnime, url);
                }
                if (StrUtil.isBlank(localAnime.getImg())){
                    localAnime.setImg("https://img2.doubanio.com/cuphead/movie-static/pics/movie_default_large.png");
                }
                localAnime.setUrl(url);
                localAnime.setDouBan(Integer.parseInt(mDouBanId.group(1)));
            }
        }
    }

    public static void supplementAnimeCover(LocalAnime localAnime, String url) {
        try {
            String result = HttpUtil.get(url, CharsetUtil.CHARSET_UTF_8);
            Matcher matcher = Pattern.compile("\"image\": \"(.*?)\"").matcher(result);
            if (matcher.find()) {
                localAnime.setImg(matcher.group(1));
            }
        } catch (Exception ignore) {
        }
    }

    private static JSONObject douBanSelect(String name, Integer num) {
        String tv_num = Convert.numberToChinese(Double.parseDouble(String.valueOf(num)), false);
        String result = HttpUtil.get("https://search.douban.com/movie/subject_search?search_text=" + name + "&cat=1002", CharsetUtil.CHARSET_UTF_8);
        Matcher matcher = Pattern.compile("window.__DATA__ = (.*?);", Pattern.DOTALL).matcher(result);
        if (matcher.find()) {
            JSONArray jsonArray = JSONUtil.parseObj(matcher.group(1)).getJSONArray("items");
            for (Object o : jsonArray) {
                JSONObject data = JSONUtil.parseObj(o);
                List<String> labelList = data.getJSONArray("labels").stream().map(label -> ((JSONObject) label).getStr("text")).filter(Objects::nonNull).collect(Collectors.toList());
                if (!labelList.isEmpty() && labelList.contains("可播放")) {
                    String d_name = data.getStr("title");
                    String d_tv_num = "";
                    Matcher matcherName = Pattern.compile("第(.*?)季").matcher(d_name);
                    if (matcherName.find()) {
                        d_tv_num = matcherName.group(1);
                    } else {
                        matcherName = Pattern.compile(name + "(\\d+)").matcher(d_name);
                        if (matcherName.find()) {
                            d_tv_num = matcherName.group(1);
                        } else {
                            List<String> romanNum = new ArrayList<>(Arrays.asList("", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"));
                            matcherName = Pattern.compile(name + "([ " + String.join("|", romanNum) + "]+)").matcher(d_name);
                            if (matcherName.find()) {
                                int index = romanNum.indexOf(matcherName.group(1));
                                if (index != -1) {
                                    d_tv_num = String.valueOf(index);
                                }
                            } else {
                                d_tv_num = "一";
                            }
                        }
                    }
                    try {
                        long d_tv_num_ps = Long.parseLong(d_tv_num);
                        d_tv_num = Convert.numberToChinese(d_tv_num_ps, false);
                    } catch (Exception ignore) {
                    }
                    if (d_name.split(" ")[0].replace("\u200E","").equals(name.split(" ")[0]) && StrUtil.containsAny(tv_num, name, d_tv_num)) {
                        return data;
                    }
                }
            }
        }
        return null;
    }

}
